# 最终干净修复脚本 - 避免复杂字符串处理
import os
import shutil

# 文件路径
original_file = r'd:\未知\yolo_apply\video_processing\video_processor.py'
final_backup = r'd:\未知\yolo_apply\video_processing\video_processor.py.final_backup'
temp_file = r'd:\未知\yolo_apply\video_processing\clean_final.py'

# 确保我们使用最终备份
if os.path.exists(final_backup):
    print(f"Using final backup file: {final_backup}")
    
    # 读取备份文件的行
    with open(final_backup, 'r', encoding='utf-8', errors='replace') as f:
        lines = f.readlines()
    
    # 找到问题区域
    start_idx = None
    end_idx = None
    
    for i, line in enumerate(lines):
        if '# 错误率过高时触发警告和恢复' in line:
            start_idx = i
        elif start_idx is not None and 'error_count = 0' in line:
            end_idx = i
            break
    
    if start_idx is not None and end_idx is not None:
        print(f"Problem area found from line {start_idx+1} to {end_idx+1}")
        
        # 创建新的文件内容
        new_lines = []
        
        # 添加问题区域之前的行
        new_lines.extend(lines[:start_idx])
        
        # 确定缩进级别
        if start_idx > 0:
            prev_line = lines[start_idx-1]
            indent = ' ' * (len(prev_line) - len(prev_line.lstrip()))
        else:
            indent = ''
        
        # 添加最小化的修复：只保留注释和error_count重置
        # 使用简单的字符串，避免复杂字符处理
        comment_line = indent + "# 错误率过高时触发警告和恢复\n"
        reset_line = indent + "error_count = 0\n"
        
        new_lines.append(comment_line)
        new_lines.append(reset_line)
        
        # 添加问题区域之后的行
        new_lines.extend(lines[end_idx+1:])
        
        # 写入临时文件
        with open(temp_file, 'w', encoding='utf-8', newline='\n') as f:
            f.writelines(new_lines)
        
        print(f"Created clean temporary file: {temp_file}")
        
        # 替换原文件
        os.replace(temp_file, original_file)
        print(f"Replaced original file with clean version")
        print("Now let's try to compile again...")
    else:
        print("Error: Could not find the problem area in the file")
else:
    print(f"Error: Could not find final backup file {final_backup}")